import ModalContent from "./ModalContent.tsx";
import useModalState from "../../settings/GlobalStates.ts";
import {useEffect, useRef, useState} from "react";
import {baseUrl} from "../../settings/Settings.ts";
import useToastState from "../../settings/ToastGlobalState.ts";
import * as bootstrap from "bootstrap";


const LibraryModal = () => {
    const closeButtonRef = useRef(null)

    const stackId = useModalState((state) => state.stackId)
    const [bookList, setBookList] = useState<Book[]>([])
    const [bookId, setBookId] = useState<Book | undefined>(null)
    const {setToastMessage} = useToastState()


    const toastLiveExample = document.getElementById('liveToast');

    const triggerToast = () => {
        const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toastLiveExample);
        toastBootstrap.show();
    };


    useEffect(() => {
        const fetchData = () => {

            if (stackId) {


                const formData = {
                    stackId: stackId
                };

                fetch(`${baseUrl}/api/books/byStackId`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(formData)
                })
                    .then(response => {
                        return response.json().then(data => ({response, data}));
                    })
                    .then(({response, data}) => {


                        if (response.ok) {
                            setBookList(data.books)
                        }

                        console.log(data);
                        // handle response from server

                    })


            }
        };


        fetchData();
    }, [stackId]);


    const addToCart = () => {
        console.log(bookId)

        if (bookId) {

            try {


                const formData = {
                    bookId: bookId
                };

                fetch(`${baseUrl}/api/cart/insert`, {
                    method: 'POST',
                    credentials: 'include',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(formData)
                })
                    .then(response => {
                        return response.json().then(data => ({response, data}));
                    })
                    .then(({response, data}) => {


                        if (response.ok) {
                            closeButtonRef.current?.click()
                        }
                        setToastMessage(data.message)
                        triggerToast()

                        console.log(data);
                        // handle response from server

                    })

            } catch (error) {
                console.error('Error fetching data')
            }
        } else {
            //show toast
        }


    }


    const {setStackId} = useModalState();

    const removeStackId = () => {
        setStackId(null)
    }


    return (

        <div className={"modal fade"} id="exampleModal" aria-labelledby="exampleModalLabel"
             aria-hidden="true">
            <div className="modal-dialog modal-dialog-centered modal-dialog-scrollable">
                <div className="modal-content">
                    <div className="modal-header">
                        <h1 className="modal-title fs-5" id="exampleModalLabel"></h1>
                        <button type="button" className="btn-close" data-bs-dismiss="modal"
                                aria-label="Close" onClick={removeStackId}></button>
                    </div>
                    <div className="modal-body">
                        <ModalContent setBookId={setBookId} bookList={bookList}/>
                    </div>

                    <div className="modal-footer">
                        <button type="button" className="btn btn-outline-secondary rounded-5 outlined-button "
                                data-bs-dismiss="modal" ref={closeButtonRef} onClick={removeStackId}>Close
                        </button>
                        <button type="button" className="btn rounded-5 primary-button" onClick={addToCart}>
                            Add to cart
                        </button>


                    </div>
                </div>
            </div>
        </div>
    )

}

export default LibraryModal